#coding=utf-8
import wx
import os
import sys
import subprocess
##print os.getcwd()
##print sys.path
from com.jumang.content.GetContent import GetContent
from com.jumang.content.BaseCheck import BaseCheck
from com.jumang.config.Config import myConfig
import urllib
import chardet
from datetime import datetime
from com.jumang.ui.statedialog import StateDialog
from com.jumang.ui.RemindDialog import RemindDialog
from com.jumang.ui.EventInterface import EventInterface
ID_TIMER=10000
ID_ALERT_TIMER=10001
from log4py import Logger
import threading

class RunInformation():
  position=0
  information='Jumang'
  def getChar(self):
    result= self.information[self.position] 
    self.position+=1
    if self.position>=len(self.information):
      self.position=0
    return result

class MainFrame(wx.Frame,EventInterface):
  originWidth=130
  originHeight=27
  alarmWidth=200
  alarmHeight=60
  originPos=(270,5) 
  stateDialog=None

  def __init__(self):
    wx.Frame.__init__(self,None,wx.ID_ANY,'',size=(self.originWidth,self.originHeight),pos=self.originPos,style=wx.STAY_ON_TOP|wx.FRAME_NO_TASKBAR)
    self.SetTransparent(170);
    self.control=wx.TextCtrl(self,wx.ID_ANY,size=(self.originWidth,self.originHeight),style=wx.TE_MULTILINE|wx.TE_READONLY)
    self.timer=wx.Timer(self,ID_TIMER)
    wx.EVT_TIMER(self,ID_TIMER,self.onTime)
    self.alertTimer=wx.Timer(self,ID_ALERT_TIMER)
    wx.EVT_TIMER(self,ID_ALERT_TIMER,self.onAlertTime)
    self.logger=Logger().get_instance('MainFrame')
    self.logger.info('System start.')
    self.servers=GetContent(self).getContent()
    self.timer.Start(myConfig.speed)
    self.hasError=False
    self.information=RunInformation()
    self.lockObj=threading.Lock()
    #self.timer.Start(100,True)
    self.control.Bind(wx.EVT_MOTION, self.onMouse)
    wx.EVT_RIGHT_UP(self.control, self.onRightClick)
    self._dragPos = None
    self.Show(True)
  
  def onMouse(self, event):
          """implement dragging"""
          if not event.Dragging():
              #self._dragPos = None
              return
          #print self
          #self.CaptureMouse()
          #print self._dragPos
          if not self._dragPos:
              self._dragPos = event.GetPosition()
          else:
              pos = event.GetPosition()
              displacement = self._dragPos - pos
              self.SetPosition( self.GetPosition() - displacement ) 
          #self.ReleaseMouse()
  
  def onTime(self,e):
    for server in self.servers:
      try:
        server.notifyCheck()
      except:
        pass
      self.control.ChangeValue(datetime.now().strftime('%m.%d %H:%M:%S')+' '+self.information.getChar())
   
  def onAlertTime(self,e):
    ##self.control.ChangeValue(getContent.getNext())
    if self.backColour:
      self.backColour=False
      self.control.SetBackgroundColour('Blue')
    else:
      self.backColour=True
      self.control.SetBackgroundColour('Red')
    self.Refresh()
    
  def onRightClick(self,e):
    menu = wx.Menu()
    logsItem=menu.Append(-1,'View log') 
    stateItem=menu.Append(-1,'View state') 
    menu.AppendSeparator()
    
    if self.alertTimer.IsRunning():
      clearItem=menu.Append(-1,'Clear')
      self.Bind(wx.EVT_MENU, self.onClear, clearItem)
    
    if self.timer.IsRunning():
      pauseItem=menu.Append(-1,'Stop')
    else:
      pauseItem=menu.Append(-1,'Start')
    checkItem=menu.Append(-1,'Check servers') 
    menu.AppendSeparator()
    editServerItem=menu.Append(-1,'Edit servers') 
    reloadServerItem=menu.Append(-1,'Reload servers')
    menu.AppendSeparator()
    exitItem=menu.Append(-1,'Exit')
    
    self.Bind(wx.EVT_MENU, self.onPause, pauseItem)
    self.Bind(wx.EVT_MENU, self.onLog, logsItem)
    self.Bind(wx.EVT_MENU, self.onExit, exitItem)
    self.Bind(wx.EVT_MENU, self.onCheck, checkItem)
    self.Bind(wx.EVT_MENU, self.onState, stateItem)
    self.Bind(wx.EVT_MENU, self.onEditServer, editServerItem)
    self.Bind(wx.EVT_MENU, self.onReloadServer, reloadServerItem)
    
    self.PopupMenu(menu, e.GetPosition())
    menu.Destroy()
  
  def onClear(self,e):
    self.hasError=False
    self.alertTimer.Stop()
    self.control.ChangeValue('')
    self.SetSize(wx.Size(self.originWidth,self.originHeight))
    self.control.SetSize(wx.Size(self.originWidth,self.originHeight))
    self.control.SetBackgroundColour(None)
    
  def onLog(self,e):
    subprocess.Popen('notepad logs.txt')
    #subprocess.spawnl(os.P_NOWAIT,'notepad.exe logs.txt')

    
  def onExit(self,e):
    exitDialog=wx.MessageDialog(self,'Are you sure?','Exit')
    if exitDialog.ShowModal()==wx.ID_CANCEL:
      exitDialog.Destroy()
      return
    self.logger.info('System closed.')
    self.Close()
    if self.stateDialog:
      self.stateDialog.Close()
    exit()
    
  def onPause(self,e):
    if self.timer.IsRunning():
      self.timer.Stop()
    else:
      self.timer.Start()
  
  def onCheck(self,e):
    for server in self.servers:
      try:
        server.forceCheck()
      except:
        pass
      self.control.ChangeValue(datetime.now().strftime('%m.%d %H:%M:%S')+' '+self.information.getChar())
    

  def onState(self,e):
    if not self.stateDialog:
      self.stateDialog=StateDialog(self)
    self.stateDialog.Show(True)
    
  def onEditServer(self,e):
    subprocess.Popen('notepad servers.txt')
    
  def onReloadServer(self,e):
    for server in self.servers:
      try:
        server.terminate()
      except:
        pass
    self.servers=GetContent(self).getContent()

    
  def notifyEvent(self,source,errorNo,errorInfo):
    self.lockObj.acquire()
    self.SetSize(wx.Size(self.alarmWidth,self.alarmHeight))
    self.control.SetSize(wx.Size(self.alarmWidth,self.alarmHeight))
    self.logger.info(source.getName()+' '+str(errorNo)+' '+str(errorInfo))
    self.control.ChangeValue(datetime.now().strftime('%m.%d %H:%M:%S'))
    self.control.AppendText(' '+source.getName()+' '+str(errorNo)+'\n')
    self.backColour=True
    wx.CallAfter(self.alertTimer.Start,myConfig.alertSpeed)
    #self.alertTimer.Start(myConfig.alertSpeed)
    self.lockObj.release()
    
  def showMessage(self,message):
    dia=RemindDialog(self,message)
    dia.Show(True)
  

app = wx.PySimpleApp()
frame = MainFrame()
app.MainLoop()
